<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="parent_id" label="父类别" v-if="!isRootCategory">
				<!-- <uni-easyinput placeholder="父ID，用于多级分类" v-model="formData.parent_id"></uni-easyinput> -->
				<ljs-treeChoose-vue3 v-model="ljs_tree.treeData" :ids="ljs_tree.chooseIds" :props="ljs_tree.props"
					:keywordsFilter="true" :checkStrictly="true" @getChooseValue="ljs_treeGetChooseValue"
					:showAllLevels="false">
				</ljs-treeChoose-vue3>
			</uni-forms-item>
			<uni-forms-item name="merchant_id" label="所属商户" v-if="!isRootCategory">
				<view class="merchant-select-wrapper">
					<uni-easyinput 
						placeholder="请输入商户名称搜索" 
						v-model="merchantInput" 
						@input="onMerchantInput"
						@focus="onMerchantFocus"
						@blur="onMerchantBlur"
						trim="both">
					</uni-easyinput>
					<view class="merchant-dropdown" v-if="showMerchantDropdown && filteredMerchants.length > 0">
						<view 
							class="merchant-item" 
							v-for="merchant in filteredMerchants" 
							:key="merchant._id"
							@click="selectMerchant(merchant)">
							<text class="merchant-name">{{ merchant.name }}</text>
							<text class="merchant-desc" v-if="merchant.description">{{ merchant.description }}</text>
						</view>
					</view>
					<view class="merchant-dropdown" v-if="showMerchantDropdown && merchantInput && filteredMerchants.length === 0">
						<view class="no-result">未找到匹配的商户</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="name" label="类别名称" required>
				<uni-easyinput placeholder="类别名称" v-model="formData.name" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput placeholder="类别排序，越大越靠后" type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="类别描述">
				<uni-easyinput placeholder="类别描述" v-model="formData.description" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="create_date" label="类别创建时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.create_date"></uni-datetime-picker>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-mall-categories.js';

	const db = uniCloud.databaseForJQL();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-mall-categories';
	const merchantCollectionName = "intangible_merchant"; // 商户表名

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"parent_id": "",
				"merchant_id": "",
				"name": "",
				"sort": null,
				"description": "",
				"create_date": null
			}
			return {
				ljs_tree: {
					treeData: [],
					chooseIds: [], // 选择tree的id数据结果集合
					props: {
						label: 'name',
						id: '_id',
						children: 'children'
					},
				},
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				// 商户选择相关数据
				merchantInput: '', // 商户输入框的值
				merchants: [], // 所有商户数据
				filteredMerchants: [], // 过滤后的商户数据
				showMerchantDropdown: false, // 是否显示下拉框
				searchTimer: null, // 搜索防抖定时器
				isRootCategory: false, // 是否为根类别
			}
		},
		onLoad(e) {
			// this.loadData()
			this.loadMerchants()
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 加载商户数据
			 */
			loadMerchants() {
				db.collection(merchantCollectionName)
					.field('_id,name,description')
					.get()
					.then((res) => {
						this.merchants = res.data || []
						console.log('加载商户数据成功:', this.merchants.length)
					})
					.catch((err) => {
						console.error('加载商户数据失败:', err)
					})
			},

			/**
			 * 商户输入框输入事件
			 */
			onMerchantInput(value) {
				this.merchantInput = value

				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
				}

				// 防抖处理，延迟300ms执行搜索
				this.searchTimer = setTimeout(() => {
					this.searchMerchants(value)
				}, 300)
			},

			/**
			 * 商户输入框获得焦点
			 */
			onMerchantFocus() {
				if (this.merchantInput) {
					this.searchMerchants(this.merchantInput)
				}
				this.showMerchantDropdown = true
			},

			/**
			 * 商户输入框失去焦点
			 */
			onMerchantBlur() {
				// 延迟隐藏下拉框，让点击事件能够触发
				setTimeout(() => {
					this.showMerchantDropdown = false
				}, 200)
			},

			/**
			 * 搜索商户
			 */
			searchMerchants(keyword) {
				if (!keyword || keyword.trim() === '') {
					this.filteredMerchants = []
					return
				}

				const searchKeyword = keyword.toLowerCase().trim()
				this.filteredMerchants = this.merchants.filter(merchant => {
					return merchant.name.toLowerCase().includes(searchKeyword)
				}).slice(0, 10) // 最多显示10个结果
			},

			/**
			 * 选择商户
			 */
			selectMerchant(merchant) {
				this.merchantInput = merchant.name
				this.formData.merchant_id = merchant._id
				this.showMerchantDropdown = false
				console.log('选择的商户:', merchant)
				
				// 重新加载该商户的类别树
				this.loadData(merchant._id)
				// 清空父类别选择
				this.ljs_tree.chooseIds = []
				this.formData.parent_id = ""
			},

			/**
			 * 类别树展开
			 * @param {String} merchantId - 商户ID，如果提供则只加载该商户的类别
			 */
			loadData(merchantId = null) {
				var that = this
				let query = db.collection(dbCollectionName)
				
				// 如果提供了商户ID，只加载该商户的类别
				console.log("loadData merchantId", merchantId);
				if (merchantId) {
					query = query.where(`merchant_id == "${merchantId}" || merchant_id == "" || merchant_id == null`)
				}
				
				query = query.field("sort,name,_id,parent_id,merchant_id")
					.orderBy("parent_id asc,sort asc")
				
				query.get({
						getTree: true
					})
					.then((res) => {
						that.ljs_tree.treeData = res.data
						console.log("treeData", that.ljs_tree.treeData);
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
			},
			ljs_treeGetChooseValue(ids, items) {
				this.formData.parent_id = ids[0]
				// console.log(ids,items)
				this.ljs_tree.chooseIds = ids;
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			async getDetail(id) {
				uni.showLoading({
					mask: true
				})
				
				db.collection(dbCollectionName).doc(id).field("parent_id,merchant_id,name,sort,description,create_date").get().then((
					res) => {
						
					const data = res.data[0]
					if (data) {
						this.formData = data
						
						// 判断是否为根类别
						this.isRootCategory = !data.parent_id || data.parent_id === ""
						
						//设置父类别
						this.ljs_tree.chooseIds = this.formData.parent_id==""?[]:[this.formData.parent_id]
						
						// 设置商户输入框显示
						if (!this.isRootCategory && data.merchant_id) {
							// 从已加载的商户列表中查找对应的商户名称
							const merchant = this.merchants.find(m => m._id === data.merchant_id)
							if (merchant) {
								this.merchantInput = merchant.name
							} else {
								// 如果本地没有，从数据库查询
								db.collection(merchantCollectionName).doc(data.merchant_id).field('_id,name').get()
									.then((merchantRes) => {
										if (merchantRes.data && merchantRes.data.length > 0) {
											this.merchantInput = merchantRes.data[0].name
										}
									})
									.catch((err) => {
										console.error('查询商户信息失败:', err)
									})
							}
							
              // 重新加载该商户的类别树
              console.log("加载类别树 merchant_id", data.merchant_id);
							this.loadData(data.merchant_id)
						} else {
							// 如果是根类别，加载所有类别树
							this.loadData()
						}
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style lang="scss">
/* 商户选择样式 */
.merchant-select-wrapper {
	position: relative;
	z-index: 99;
}

.merchant-dropdown {
	position: absolute;
	top: 100%;
	left: 0;
	right: 0;
	background-color: #fff;
	border: 1px solid #ddd;
	border-top: none;
	border-radius: 0 0 6px 6px;
	max-height: 200px;
	overflow-y: auto;
	z-index: 99;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.merchant-item {
	padding: 12px 16px;
	border-bottom: 1px solid #f5f5f5;
	cursor: pointer;
	transition: background-color 0.2s;

	&:hover {
		background-color: #f8f9fa;
	}

	&:last-child {
		border-bottom: none;
	}

	.merchant-name {
		display: block;
		font-size: 14px;
		color: #333;
		font-weight: 500;
		margin-bottom: 4px;
	}

	.merchant-desc {
		display: block;
		font-size: 12px;
		color: #999;
		line-height: 1.4;
	}
}

.no-result {
	padding: 16px;
	text-align: center;
	color: #999;
	font-size: 14px;
}
</style>
